import { AxiosRequestConfig, AxiosPromise, AxiosResponse } from './types'
import { parseHeaders } from './helpers/header'

export default function xhr(config: AxiosRequestConfig): AxiosPromise {
  return new Promise((resolve, reject) => {
    const { data = null, method = 'get', url, headers, responseType } = config
    const request = new XMLHttpRequest()

    if (responseType) {
      request.responseType = responseType
    }

    request.onreadystatechange = () => {
      if (request.readyState === 4) {
        const data = responseType !== 'text' ? request.response : request.responseText
        const headers = parseHeaders(request.getAllResponseHeaders())

        resolve({
          data,
          status: request.status,
          statusText: request.statusText,
          request,
          headers,
          config
        })
      }
    }

    request.open(method.toUpperCase(), url, true)

    Object.keys(headers).forEach(name => request.setRequestHeader(name, headers[name]))

    request.send(data)
  })
}
